import webapp2
import logging
import os

from google.appengine.ext.webapp import template

from model.message import Message
from model.user    import User
from model.room    import Room



class HistoryPage(webapp2.RequestHandler):
    """Page that shows history of all messages for one of the users."""
    
    def get(self, username):
        user = User.all().filter("username", username).get()
        if not user:
            logging.error("Recieved history request for inexisting user %s" %
                username)
            self.redirect(webapp2.uri_for("main"))
            return
        
        # Get all messages for the user and organise them in dictionary with
        # key-value pairs <room key: messages in that room>.
        messages_query = Message.all()
        history_dict   = { }
        messages_count = 0
        for m in messages_query.run():
            messages_count += 1
            # If message "to" or "from" given user.
            if (user.key() == m.sender.key()) or (user.key() in m.recipients):
                # Add to history.
                room_key = m.room.key()
                if history_dict.has_key(room_key):
                    history_dict[room_key].append(m)
                else:
                    history_dict[room_key] = [m]
        
        # Convert the dictionary into a list of pairs (Room object, messages in
        # that room).
        history_list = []
        for room_key, messages in history_dict.iteritems():
            history_list.append((Room.get(room_key), messages))
        
        logging.debug("History for user %s has %d messages and %d rooms" %
            (username, messages_count, len(history_list)))
        logging.debug("HISTORY: " + str(history_list))
        
        template_values = {
            "history": history_list
        }
        template_path = os.path.join(os.path.dirname(__file__), '../templates/history.html')
        self.response.out.write(template.render(template_path, template_values))